import { createRouter, createWebHistory } from 'vue-router'

import LayOut from '@/LayOut'
import { isLogin } from '@u'

const routes = [
  {
    path: '/',
    component: LayOut,
    children: [
      {
        path: '/',
        redirect: '/dashBoard'
      },
      {
        path: '/dashBoard',
        name: '首页',
        meta: {
          roles: ['*']
        },
        component: () => import('@v/DashBoard')
      },
      {
        path: '/itemLists',
        name: '商品列表',
        meta: {
          roles: ['admin']
        },
        component: () => import('@v/ItemLists')
      },
      {
        path: '/itemAdd',
        name: '添加商品',
        meta: {
          roles: ['admin']
        },
        component: () => import('@v/ItemAdd')
      },
      {
        path: '/itemUpdate',
        name: '修改商品',
        meta: {
          roles: ['admin']
        },
        component: () => import('@v/ItemUpdate')
      },
      {
        path: '/cateLists',
        name: '商品分类',
        meta: {
          roles: ['admin']
        },
        component: () => import('@v/CateLists')
      },
      {
        path: '/userInfo',
        name: '个人中心',
        meta: {
          roles: ['admin']
        },
        component: () => import('@v/UserInfo')
      },
      {
        path: '/setting',
        name: '设置',
        meta: {
          roles: ['admin']
        },
        component: () => import('@v/SettingPage')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      roles: ['*']
    },
    component: () => import('@v/LoginPage')
  },
  {
    path: '/:pathMatch(.*)*',
    component: () => import('@v/NotFound')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, form, next) => {
  if (to.path !== '/login') {
    if (isLogin()) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
